import java.util.ArrayList;
import java.util.List;
import java.io.*;

// 学生管理系统类，管理学生信息
public class StudentManagementSystem {
    private List<Student> students = new ArrayList<>();
    private static final String FILE_NAME = "students.dat";

    // 添加学生
    public void addStudent(Student student) {
        students.add(student);
    }

    // 删除学生
    public void removeStudent(int id) {
        students.removeIf(student -> student.getId() == id);
    }

    // 修改学生信息
    public void updateStudent(Student updatedStudent) {
        for (int i = 0; i < students.size(); i++) {
            if (students.get(i).getId() == updatedStudent.getId()) {
                students.set(i, updatedStudent);
                return;
            }
        }
    }

    // 查询所有学生
    public List<Student> getAllStudents() {
        return new ArrayList<>(students);
    }

    // 根据ID查询学生
    public Student getStudentById(int id) {
        for (Student student : students) {
            if (student.getId() == id) {
                return student;
            }
        }
        return null;
    }

    // 保存学生数据到文件
    public void saveStudentsToFile() throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_NAME))) {
            oos.writeObject(students);
            System.out.println("学生数据已成功保存到文件 " + FILE_NAME);
        }
    }

    // 从文件加载学生数据
    public void loadStudentsFromFile() throws IOException, ClassNotFoundException {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_NAME))) {
            students = (List<Student>) ois.readObject();
            System.out.println("学生数据已成功从文件 " + FILE_NAME + " 加载");
        }
    }
}